package com.shuinfo.service.Impl;

import com.alibaba.fastjson.JSON;
import com.shuinfo.bean.ao.WechatLeadLoginAO;
import com.shuinfo.bean.dto.WechatAccessTokenOpenIdDTO;
import com.shuinfo.bean.dto.WechatCheckUserStatusDTO;
import com.shuinfo.bean.dto.WechatCgiBinUserInfoDTO;
import com.shuinfo.bean.dto.WechatUserInfoDTO;
import com.shuinfo.bean.entity.Hzwechat;
import com.alibaba.fastjson.TypeReference;
import com.shuinfo.bean.entity.Member;
import com.shuinfo.bean.entity.WechatPacketBind;
import com.shuinfo.dao.MemberDao;
import com.shuinfo.dao.UserDao;
import com.shuinfo.service.HzwechatService;
import com.shuinfo.service.WechatPacketBindService;
import com.shuinfo.service.WechatService;
import com.shuinfo.utils.RequestUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class WechatServiceImpl implements WechatService {
    @Resource
    private UserDao userDao;

    @Resource
    private HzwechatService hdfwechatService;

    @Resource
    private WechatPacketBindService wechatPacketBindService;

    @Resource
    private MemberDao memberDao;



    @Value("${wechat.appId}")
    private String appId;


    @Value("${wechat.appSecret}")
    private String appSecret;

    @Override
    public WechatCheckUserStatusDTO checkUserStatus(String code, String paramId) {
        // step 1 换openId
        WechatUserInfoDTO wechatUserInfoDTO = getUserInfoByCode(code);
        // 结果返回体
        WechatCheckUserStatusDTO wechatCheckUserStatusDTO = new WechatCheckUserStatusDTO();

        // 根据paramId在红包用户绑定表找是否有记录，有更新，没有插入
        WechatPacketBind wechatPacketBind = wechatPacketBindService.detailByParamId(paramId);
        // 如果存在则更新paramId
        if (wechatPacketBind != null && !Objects.equals(wechatPacketBind.getOpenId(), wechatUserInfoDTO.getOpenId())){
            wechatPacketBindService.updateOpenIdByParamId(paramId, wechatUserInfoDTO.getOpenId());
        }else {
            wechatPacketBindService.insert(wechatUserInfoDTO.getOpenId(), paramId, 1, 0);
        }
        // step 2 查询openId在微信用户表里是否存在
        Hzwechat hzwechat = hdfwechatService.detailByOpenId(wechatUserInfoDTO.getOpenId());

        // step 2.1 如果用户不存在，直接返回
        if (hzwechat == null) {
            // step 2.1 登录失败
            wechatCheckUserStatusDTO.setAbleCollect(0);
            wechatCheckUserStatusDTO.setExist(0);
        }else{
            // step 2.2 如果用户存在
            wechatCheckUserStatusDTO.setExist(1);
            // step 3 检查用户是否有领取资格
            // step 3.1 如果关注了
            if (wechatUserInfoDTO.getSubscribe() == 1){
                wechatCheckUserStatusDTO.setAbleCollect(1);
                return wechatCheckUserStatusDTO;
            }else{
                // step 3.1 如果没有关注了
                wechatCheckUserStatusDTO.setAbleCollect(0);
            }
        }
        return wechatCheckUserStatusDTO;
    }

    @Override
    public boolean leadLogin(WechatLeadLoginAO req) {

        Member member = new Member();
        member.setAvatar(req.getHeadImg());
        member.setPhone(req.getPhone());
        member.setCountry(req.getCountry());
        member.setProvince(req.getProvince());
        member.setCity(req.getCity());
        member.setCreatedAt(new Date());
        member.setUpdatedAt(new Date());

        int insertResult = memberDao.insert(member);

        return insertResult == 1;
    }

    /**
     * 获取用户微信相关的信息
     * @param code
     * @return
     */
    public WechatUserInfoDTO getUserInfoByCode(String code) {
        // 获取accessToken和openId
        WechatAccessTokenOpenIdDTO wechatAccessTokenOpenIdDTO = getAccessTokenOpenIdByCode(code);
        // 换取是否关注
        String snsUserInfo = getSnsUserInfo(wechatAccessTokenOpenIdDTO.getAccessToken(), wechatAccessTokenOpenIdDTO.getOpenId());
        // 换取基本信息
        String userInfoAll = getCgiBinUserInfo(wechatAccessTokenOpenIdDTO.getAccessToken(), wechatAccessTokenOpenIdDTO.getOpenId());

        WechatUserInfoDTO wechatUserInfoDTO = new WechatUserInfoDTO();
        log.info("WechatService getUserInfoByCode wechatUserInfoDTO:{}", JSON.toJSONString(wechatUserInfoDTO));

        return wechatUserInfoDTO;
    }


    public String getSnsUserInfo(String accessToken, String openId){
        String requestUrl = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId);
        String resultStr = RequestUtil.sendGet(requestUrl);
        log.info("WechatService getSnsUserInfo requestUrl:{}, resultStr:{}", requestUrl, resultStr);
        return resultStr;
    }

    public String getCgiBinUserInfo(String accessToken, String openId){
        String requestUrl = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId);
        String resultStr = RequestUtil.sendGet(requestUrl);
        log.info("WechatService getCgiBinUserInfo requestUrl:{}, resultStr:{}", requestUrl, resultStr);
//        WechatCgiBinUserInfoDTO wechatUserInfoDTO = JSON.parseObject(resultStr, new TypeReference<WechatCgiBinUserInfoDTO>() {
//        });
        return resultStr;
    }

    /**
     * 获取accessToken和openid
     * @param code
     * @return
     */
    public WechatAccessTokenOpenIdDTO getAccessTokenOpenIdByCode(String code) {
        String requestUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, appSecret, code);
        String resultStr = RequestUtil.sendGet(requestUrl);
        log.info("WechatService getAccessTokenOpenIdByCode resultStr:{}", resultStr);

        WechatAccessTokenOpenIdDTO wechatAccessTokenOpenIdDTO = JSON.parseObject(resultStr, new TypeReference<WechatAccessTokenOpenIdDTO>() {
        });

        return wechatAccessTokenOpenIdDTO;
    }
}
